package aop;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import javax.print.attribute.standard.PDLOverrideSupported;
import java.lang.reflect.Method;

/**
 * @BelongsProject: springboot_demo
 * @BelongsPackage: aop
 * @Author: 江岸
 * @CreateTime: 2021-05-25 10:59
 * @Description: 基于CGlib的动态代理
 */
public class CGlibAgent implements MethodInterceptor {
    private Object proxy;

    public Object getInstance(Object proxy){
        this.proxy=proxy;
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(this.proxy.getClass());
        //回调方法
        enhancer.setCallback(this);
        //创建代理对象
        return enhancer.create();
    }


    //回调方法
    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println(">>>>before invoking");
        Object invoke = methodProxy.invokeSuper(o, objects);
        System.out.println(">>>>after");
        return invoke;
    }


    public static void main(String[] args) {
        CGlibAgent cGlibAgent = new CGlibAgent();
        Apple apple = (Apple) cGlibAgent.getInstance(new Apple());
        apple.show();
    }
}
